package com.ele.Dao.DaoImpl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import cn.hutool.db.handler.BeanHandler;
import com.ele.Dao.FoodCategoryDao;
import com.ele.Pojo.FoodCategory;
import com.ele.Utils.JDBCUtils;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.List;

public class FoodCategoryDaoImpl implements FoodCategoryDao {
    private DataSource dataSource = JDBCUtils.getDs();

    @Override
    public Integer foodCategoryAdd(String categoryName, String shopId) throws SQLException {
        return Db.use(dataSource).insert(
                Entity.create("food_category")
                        .set("category_name",categoryName)
                        .set("shop_id",shopId));
    }

    public Integer foodCategoryDelete(String categoryId) throws SQLException {
        return Db.use(dataSource).del("food_category","category_id",categoryId);
    }

    public Integer foodCategoryUpdate(String categoryName , String categoryId) throws SQLException{
        return Db.use(dataSource).update(
                Entity.create().set("category_name",categoryName) ,
                Entity.create("food_category").set("category_id",categoryId));
    }

    /**
     * 分页查询
     */
    public List<FoodCategory> findFoodCategory(String currentPage, String pageSize, String shopId) throws SQLException {
        Integer page = 1;
        Integer size = 5;
        if(StrUtil.isNotBlank(currentPage)){
            page = Integer.valueOf(currentPage);
        }
        if(StrUtil.isNotBlank(pageSize)){
            size = Integer.parseInt(pageSize);
        }
        page = (page -1) * size;
        return Db.use(dataSource).query("select * from food_category where shop_id = ? limit ? , ? " ,
                FoodCategory.class ,shopId , page, size );
    }

    public Long foodCategoryCount(String shopId) throws SQLException {
        return Db.use(dataSource).count(Entity.create("food_category").set("shop_id",shopId));
    }

    @Override
    public List<FoodCategory> findAllFoodCategory(String shopId) throws SQLException {
        return Db.use(dataSource).query("select * from food_category where shop_id = ?" , FoodCategory.class , shopId);
    }

    @Override
    public FoodCategory findFoodCategoryById(Integer categoryId) throws SQLException {
        return Db.use(dataSource).query("select * from food_category where category_id = ? " , BeanHandler.create(FoodCategory.class), categoryId);
    }

}
